package com.mingtu.guards.fragment;

import android.os.Build;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SpacesItemDecoration;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.FliteDequAdapter;
import com.mingtu.guards.adapter.InfrareGroupPictureAdapter;
import com.mingtu.guards.bean.InfraredRecordImgBean;
import com.mingtu.guards.utils.MyConstant;
import com.mingtu.guards.utils.MySPTools;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

import butterknife.BindView;

import static com.mingtu.guards.utils.MyConstant.ItemDecorationSpaces;

public class InfraredRecordFragment1 extends BaseFragment implements LazyFragmentPagerAdapter.Laziable {


    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;
    @BindView(R.id.empty_layout)
    EmptyDataLayout emptyLayout;

    private int currentPage = 1;
    private boolean isLoadMore = true;
    private int PAGE_SIZE = 32;
    private InfrareGroupPictureAdapter infrareGroupPictureAdapter;
    private List<InfraredRecordImgBean.DataBean.ListBean> DataBean = new ArrayList<>();
    private static final String ARG_PARAM = "param";
    private String cameraName;
    private List<String> cameraNameList;
    private static FliteDequAdapter fliteDequAdapter;

    public static InfraredRecordFragment1 getInstance(String cameraName, FliteDequAdapter adapter) {
        InfraredRecordFragment1 fragment1 = new InfraredRecordFragment1();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_PARAM, cameraName);
        fragment1.setArguments(bundle);
        fliteDequAdapter = adapter;
        return fragment1;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            cameraName = getArguments().getString(ARG_PARAM);
        }
        if (cameraName != null) {
            cameraNameList = new ArrayList<>();
            cameraNameList.add(cameraName);
        } else {
            if (fliteDequAdapter != null) {
                cameraNameList = fliteDequAdapter.getDequNameList();
            }
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_infrared_record_picture1;
    }

    @Override
    protected void initData() {
        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        recycler.setLayoutManager(manager1);
        recycler.addItemDecoration(new SpacesItemDecoration(0, 0, ItemDecorationSpaces, ItemDecorationSpaces, 0));

        infrareGroupPictureAdapter = new InfrareGroupPictureAdapter(getActivity(), context);
        recycler.setAdapter(infrareGroupPictureAdapter);
    }

    @Override
    protected void initView(View view) {

    }

    @Override
    protected void getData() {
        initListener();
        getPictureList(1);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        fliteDequAdapter = null;
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                currentPage = 1;
                getPictureList(1);
            }
        });
    }

    private void initLoadMoreListener() {
        srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(DataBean, PAGE_SIZE);
                    getPictureList(currentPage);
                }
                srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }


    public void flitePic(FliteDequAdapter fliteDequAdapter) {
        if (fliteDequAdapter != null) {
            cameraNameList = fliteDequAdapter.getDequNameList();
        }
        getPictureList(1);
    }

    public void resetData() {
        SPStaticUtils.put(MySPTools.picFliteBeginTime, "");
        SPStaticUtils.put(MySPTools.picFliteEndTime, "");

        cameraNameList = null;
        DataBean.clear();
        fliteDequAdapter = null;
        getPictureList(1);
    }

    public void refresh() {
        getPictureList(1);
    }


    /**
     * 照片列表
     */
    private void getPictureList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }

        String beginTime = SPStaticUtils.getString(MySPTools.picFliteBeginTime);
        String endTime = SPStaticUtils.getString(MySPTools.picFliteEndTime);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", PAGE_SIZE);
//        hashMap.put("cameraName", cameraName);
        hashMap.put("cameraNameList", cameraNameList);
        hashMap.put("beginTime", beginTime);
        hashMap.put("endTime", endTime);
        hashMap.put("status", 1);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_INF_RECORD_LIST)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            InfraredRecordImgBean infraredRecordImgBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                infraredRecordImgBean = new InfraredRecordImgBean();
                                infraredRecordImgBean = gson.fromJson(result, InfraredRecordImgBean.class);
                                List<InfraredRecordImgBean.DataBean.ListBean> dataBeans = infraredRecordImgBean.getData().getList();

                                try {
                                    emptyLayout.setIsShowView(false);
                                    recycler.setVisibility(View.VISIBLE);

                                    if (dataBeans != null) {

                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % PAGE_SIZE == 0 ? true : false;
                                        if (!isLoadMore) {
                                            if (currentPage > 1) {
                                                ToastUtils.showLong(getResources().getString(R.string.text_no_more_data));
                                            } else {
                                                if (dataBeans.size() == 0) {
                                                    //显示占位图
                                                    emptyLayout.setIsShowView(true);
                                                    recycler.setVisibility(View.GONE);
                                                }

                                            }
                                        }

                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            DataBean.clear();
                                            infrareGroupPictureAdapter.clearData();
                                        }

                                        //方式一  按照date方式展示
//                                        for (int i = 0; i < dataBeans.size(); i++) {
//                                            String date = dataBeans.get(i).getDate();
//                                            String myDate = "";
//                                            if (date.contains("2019")) {
//                                                String createTime = dataBeans.get(i).getCreateTime();
//                                                String[] timeArray2 = createTime.split(" ");
//                                                if (timeArray2.length > 1) {
//                                                    myDate = timeArray2[0];
//                                                    dataBeans.get(i).setTime(timeArray2[1]);
//                                                }
//
//                                            } else {
//                                                String[] timeArray1 = date.split("/");
//                                                if (timeArray1.length == 3) {
//                                                    myDate = timeArray1[2] + "-" + timeArray1[0] + "-" + timeArray1[1];
//                                                } else {
//                                                    String createTime = dataBeans.get(i).getCreateTime();
//                                                    String[] timeArray2 = createTime.split(" ");
//                                                    if (timeArray2.length > 1) {
//                                                        myDate = timeArray2[0];
//                                                    }
//                                                }
//
//                                            }
//                                            dataBeans.get(i).setDate(myDate); //替换date的值
//                                        }

                                        //方式二  按照createTime方式展示
                                        for (int i = 0; i < dataBeans.size(); i++) {
                                            String createTime = dataBeans.get(i).getCreateTime();
                                            String[] timeArray = createTime.split(" ");
                                            if (timeArray.length > 1) {
                                                String time1 = timeArray[0];
                                                dataBeans.get(i).setDate(time1); //替换date的值
                                            }
                                        }

                                        DataBean.addAll(dataBeans);
                                        //按照日期进行分组,且顺序保持不变 时间为键
                                        LinkedHashMap<String, List<InfraredRecordImgBean.DataBean.ListBean>> groupMap = DataBean.stream().collect(Collectors.groupingBy(InfraredRecordImgBean.DataBean.ListBean::getDate, LinkedHashMap::new, Collectors.toList()));
                                        infrareGroupPictureAdapter.upData(groupMap);


                                    } else {
                                        if (currentPage == 1) {
                                            //显示占位图
                                            recycler.setVisibility(View.GONE);
                                            emptyLayout.setIsShowView(true);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JsonSyntaxException e) {

                                e.printStackTrace();
                                isLoadMore = false;
                                emptyLayout.setIsShowView(true);
                                recycler.setVisibility(View.GONE);
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));

                            }

                        }
                    }
                });
    }

}